<?php

namespace app\common\model;

use think\Db;
use think\Model;

/**
 * 会员模型
 */
class User extends Model
{

    // 开启自动写入时间戳字段
    protected $autoWriteTimestamp = 'int';
    // 定义时间戳字段名
    protected $createTime = 'createtime';
    protected $updateTime = 'updatetime';
    // 追加属性
    protected $append = [
        'url',
    ];

    /**
     * 获取个人URL
     * @param string $value
     * @param array  $data
     * @return string
     */
    public function getUrlAttr($value, $data)
    {
        return "/u/" . $data['id'];
    }

    /**
     * 获取头像
     * @param string $value
     * @param array  $data
     * @return string
     */
    public function getAvatarAttr($value, $data)
    {
        if (!$value) {
            //如果不需要启用首字母头像，请使用
            //$value = '/assets/img/avatar.png';
            $value = letter_avatar($data['nickname']);
        }
        return $value;
    }

    /**
     * 获取会员的组别
     */
    public function getGroupAttr($value, $data)
    {
        return UserGroup::get($data['group_id']);
    }

    /**
     * 获取验证字段数组值
     * @param string $value
     * @param array  $data
     * @return  object
     */
    public function getVerificationAttr($value, $data)
    {
        $value = array_filter((array)json_decode($value, true));
        $value = array_merge(['email' => 0, 'mobile' => 0], $value);
        return (object)$value;
    }

    /**
     * 设置验证字段
     * @param mixed $value
     * @return string
     */
    public function setVerificationAttr($value)
    {
        $value = is_object($value) || is_array($value) ? json_encode($value) : $value;
        return $value;
    }

    /**
     * 变更会员余额
     * @param int    $money   余额
     * @param int    $user_id 会员ID
     * @param string $memo    备注
     */
    public static function money($money, $user_id, $memo)
    {
        Db::startTrans();
        try {
            $user = self::lock(true)->find($user_id);
            if ($user && $money != 0) {
                $before = $user->money;
                //$after = $user->money + $money;
                $after = function_exists('bcadd') ? bcadd($user->money, $money, 2) : $user->money + $money;
                //更新会员信息
                $user->save(['money' => $after]);
                //写入日志
                MoneyLog::create(['user_id' => $user_id, 'money' => $money, 'before' => $before, 'after' => $after, 'memo' => $memo]);
            }
            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
        }
    }

    /**
     * 变更会员积分
     * @param int    $score   积分
     * @param int    $user_id 会员ID
     * @param string $memo    备注
     * $is_fixed 0 自由 1固定
     */
    public static function score($score, $user_id, $memo,$is_fixed=0,$merchant_user_id=0,$order_id=0,$end_time=0,$is_cz=0)
    {
        Db::startTrans();
        try {
            $user = self::lock(true)->find($user_id);
            if ($user && $score != 0) {
                $surplus_score = 0;
                //更新会员信息
                if($is_fixed == 0){
                    $before = $user->score;
                    $after = $user->score + $score;
                    $level = self::nextlevel($after);
                    $user->save(['score' => $after, 'level' => $level]);
                }else{
                    if($score < 0){

                        self::fixedScorexh($score,$user_id,$merchant_user_id);
                    }else{
                        $surplus_score = $score;
                    }
                    $before = $user->fixed_score;
                    $after = $user->fixed_score + $score;
                    $level = self::nextlevel($after);
                    $user->save(['fixed_score' => $after, 'level' => $level]);
                }

                //写入日志
                ScoreLog::create(['user_id' => $user_id, 'score' => $score, 'before' => $before, 'after' => $after, 'memo' => $memo, 'is_fixed' => $is_fixed, 'merchant_user_id' => $merchant_user_id,'order_id'=>$order_id,'end_time'=>$end_time,'surplus_score'=>$surplus_score,'is_cz'=>$is_cz]);
            }
            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
        }
    }

    /**
     * @param $score
     * @param $user_id
     * @param $merchant_user_id
     * @return void
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     * 减少剩余积分
     */
    public static function fixedScorexh($score,$user_id,$merchant_user_id){

        $score = abs($score);
        $list = Db::name("user_score_log")
            ->where(['end_time'=>['>',time()],'surplus_score'=>['>',0],'is_fixed'=>1,'user_id'=>$user_id,'merchant_user_id'=>$merchant_user_id])
            ->order("id asc")
            ->select();

        foreach ($list as $k=>$v){
            if($v['surplus_score'] > $score){
                $e_score = $v['surplus_score'] - $score;
                Db::name("user_score_log")->where(['id'=>$v['id']])->update(['surplus_score'=>$e_score]);
                break;
            }else{
                $e_score = $score - $v['surplus_score'];
                Db::name("user_score_log")->where(['id'=>$v['id']])->update(['surplus_score'=>0]);
                self::fixedScorexh($e_score,$user_id,$merchant_user_id);
            }
        }
    }

    /**
     * 根据积分获取等级
     * @param int $score 积分
     * @return int
     */
    public static function nextlevel($score = 0)
    {
        $lv = array(1 => 0, 2 => 30, 3 => 100, 4 => 500, 5 => 1000, 6 => 2000, 7 => 3000, 8 => 5000, 9 => 8000, 10 => 10000);
        $level = 1;
        foreach ($lv as $key => $value) {
            if ($score >= $value) {
                $level = $key;
            }
        }
        return $level;
    }
    public static function userCouponUse($user_id=0,$money=0,$merchant_user_id=0,$ids='',$dk_money=0){
        //echo $money."_".$ids."------";
        $coupon_where['use_begtime'] = ['<',time()];
        $coupon_where['use_endtime'] = ['>',time()];
        $where1['merchant_user_id'] = $merchant_user_id;
        $where1['type'] = 2;
        $where2['type'] = 1;
        $sy_zf = $money - $dk_money;
        if($sy_zf == 0){
            $re_data['ids'] = trim($ids,',');
            $re_data['dk_money'] = $dk_money;
            return $re_data;
        }
       /* */
        //$merchant_user_coupon1 = Db::name("user_coupon")->where($where1)->where($coupon_where)->where(['user_id'=>$user_id,'money'=>['<=',$money],'is_used'=>1,'number'=>['<=',$money],'id'=>['not in', trim($ids,',')]])->order("number desc")->find();
        $merchant_user_coupon1 = Db::name("user_coupon")->where($where1)->where($coupon_where)->where(['user_id'=>$user_id,'money'=>['<=',$money],'is_used'=>1,'id'=>['not in', trim($ids,',')]])->order("number desc")->find();

        $merchant_user_coupon2 = Db::name("user_coupon")->where($where2)->where($coupon_where)->where(['user_id'=>$user_id,'money'=>['<=',$money],'is_used'=>1,'id'=>['not in', trim($ids,',')]])->order("number desc")->find();
        //$merchant_user_coupon2 = Db::name("user_coupon")->where($where2)->where($coupon_where)->where(['user_id'=>$user_id,'money'=>['<=',$money],'is_used'=>1,'number'=>['<=',$money],'id'=>['not in', trim($ids,',')]])->order("number desc")->find();
        if($merchant_user_coupon1 && $merchant_user_coupon2){
            if($merchant_user_coupon1['number'] > $merchant_user_coupon2['number']){
                if($sy_zf > $merchant_user_coupon1['number']){
                    $end_money = $merchant_user_coupon1['number'];
                }else{
                    $end_money = $sy_zf;
                }
                $sy_money = $money - $merchant_user_coupon1['money'];
                $ids = $ids.','.$merchant_user_coupon1['id'];
                $dk_money += $end_money;
                return self::userCouponUse($user_id,$sy_money,$merchant_user_id,$ids,$dk_money);
            }else{
                if($sy_zf > $merchant_user_coupon2['number']){
                    $end_money = $merchant_user_coupon2['number'];
                }else{
                    $end_money = $sy_zf;
                }
                $sy_money = $money -$merchant_user_coupon2['money'];
                $ids = $ids.','.$merchant_user_coupon2['id'];
                $dk_money += $end_money;
                return self::userCouponUse($user_id,$sy_money,$merchant_user_id,$ids,$dk_money);
            }
        }elseif($merchant_user_coupon1){
            if($sy_zf > $merchant_user_coupon1['number']){
                $end_money = $merchant_user_coupon1['number'];
            }else{
                $end_money = $sy_zf;
            }
            $sy_money = $money -$merchant_user_coupon1['money'];
            $ids = $ids.','.$merchant_user_coupon1['id'];
            $dk_money += $end_money;
            return self::userCouponUse($user_id,$sy_money,$merchant_user_id,$ids,$dk_money);
        }elseif($merchant_user_coupon2){
            if($sy_zf > $merchant_user_coupon2['number']){
                $end_money = $merchant_user_coupon2['number'];
            }else{
                $end_money = $sy_zf;
            }
            $sy_money = $money - $merchant_user_coupon2['money'];
            $ids = $ids.','.$merchant_user_coupon2['id'];
            $dk_money += $end_money;
            return self::userCouponUse($user_id,$sy_money,$merchant_user_id,$ids,$dk_money);
        }else{
            $re_data['ids'] = trim($ids,',');
            $re_data['dk_money'] = $dk_money;
            return $re_data;
        }

    }
}
